import 'dart:io';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:laos_mall/common/style/app_style.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shimmer/shimmer.dart';
import 'package:skeletonizer/skeletonizer.dart';

extension PaddingExt on Widget {
  Widget addPadding(EdgeInsetsGeometry padding) =>
      Padding(padding: padding, child: this);

  Widget addOpacity(double opacity) => Opacity(opacity: opacity,child: this);

  Widget addGestureTap(GestureTapCallback onTap) => GestureDetector(
      behavior: HitTestBehavior.opaque, onTap: onTap, child: this);

  Widget addWillPop(bool canPop,BuildContext context,{PopInvokedCallback? onPopInvoked}){
    return PopScope(onPopInvoked: onPopInvoked, child: this);
    // return WillPopScope(onWillPop: (){
    //   if(Navigator.of(context).canPop()){
    //     return Future.value(false);
    //   }
    //   return Future.value(true);
    //   },child: this);
  }

  Widget addRadius(double radius, {BorderRadius? borderRadius}) => ClipRRect(
      borderRadius: borderRadius ?? BorderRadius.circular(radius), child: this);

  Widget addCircleAvatar() => ClipOval(child: this);

  Widget addSizeBox(double width, double height) =>
      SizedBox(width: width, height: height, child: this);

  Widget addSingleChildScrollView({ScrollController? controller}) =>
      SingleChildScrollView(controller: controller, child: this);

  Widget addExpand() => Expanded(child: this);

  Widget addCenter() => Center(child: this);

  Widget addVisibility(bool visible) =>
      Visibility(visible: visible, child: this);

  Widget addOffstage(bool offstage) =>
      Offstage(offstage: !offstage, child: this);

  Widget addMenuButton(PopupMenuItemBuilder itemBuilder,
      {Offset offset = Offset.zero, Icon? icon}) {
    return PopupMenuButton(
      itemBuilder: itemBuilder,
      offset: offset,
      icon: icon,
      child: this,
    );
  }

  Widget addClipRRect(BorderRadius borderRadius) {
    return ClipRRect(borderRadius: borderRadius, child: this);
  }

  Widget addSliverToBox() => SliverToBoxAdapter(child: this);

  Widget addTransform(){
    return Transform.rotate(angle: pi,child: this,);
  }
  Widget addSliverFillRemaining() => SliverFillRemaining(child: this);

  Widget addDiver({double? indent,bool visible = true}){
    return Column(children: [
      this,
       Divider(color: const Color(0xFFE6E6E6),indent: indent,endIndent: indent,height: 0.5,).addVisibility(visible)
    ],);
  }

  Widget addSkeleton({bool isDismiss = false,bool? ignoreContainers}){
     // return Skeletonizer(enabled: true,ignoreContainers: ignoreContainers ?? false, child: this,enableSwitchAnimation: false,);

    return Shimmer.fromColors(
      baseColor: AppColor.dividerColor,
      highlightColor: AppColor.textColor2,
      child: this,
      loop: 3,
    );
  }

  Widget addBadge(int count,{Offset? offset,bool isBottomBar = false}){
    return Badge.count(count: count,offset:offset, child: this,isLabelVisible: count > 0,);
  }

  ObxWidget addObx(){
     return  Obx(() {
      return this;
    });
  }

  // Widget getTextSize(String text, TextStyle style,{bool? isThis = true}) {
  //   final TextPainter textPainter = TextPainter(
  //       text: TextSpan(text: text, style: style), maxLines: 1, textDirection: TextDirection.ltr)
  //     ..layout(minWidth: 0, maxWidth: double.infinity);
  //   return SizedBox(width: textPainter.width,height: textPainter.height);
  // }

  Widget addContainer(
      {Color color = Colors.white,
      double? width,
      double? height,
      EdgeInsetsGeometry? padding,
      AlignmentGeometry? alignment,
      EdgeInsetsGeometry? margin,
      double radius = 0,
      isShadow = false,
      ShapeBorder? border,
      List<Color>? gradientColors,
        BoxConstraints?  constraints
      }) {
    getDecoration() {
      Decoration decoration;
      if (border == null) {
        decoration = BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(radius),
            boxShadow: isShadow
                ? [
                    const BoxShadow(
                        color: Colors.black12,
                        offset: Offset(3.0, 3.0), //阴影xy轴偏移量
                        blurRadius: 5.0, //阴影模糊程度
                        spreadRadius: 2.0 //阴影扩散程度
                        )
                  ]
                : null);
      } else {
        decoration = ShapeDecoration(
            shape: border,
            color: color,
            shadows: isShadow
                ? [
                    const BoxShadow(
                        color: Colors.black38,
                        offset: Offset(3.0, 3.0), //阴影xy轴偏移量
                        blurRadius: 20.0, //阴影模糊程度
                        spreadRadius: 2.0 //阴影扩散程度
                        )
                  ]
                : null);
      }
      return decoration;
    }

    return Container(
        alignment: alignment,
        padding: padding,
        margin: margin,
        width: width,
        height: height,
        decoration: getDecoration(),
        constraints: constraints,
        child: this);
  }
}

extension ImageExt on Image {
  Image addImageType({String? filPath, String? name, String? url}) {
    if (filPath != null) {
      return Image.file(File(filPath), width: width, height: height, fit: fit);
    }
    return this;
  }
}

class Utils {
  Utils._();
  static String getImgPath(String name,
      {String format = 'png', String? directory}) {
    return name.toImgPath(format: format, directory: directory);
  }

  static Widget getSvgImage(
    String name, {
    String format = 'svg',
    double? width = 20,
    String? directory = "svg",
    double? height,
    Color? color,
    BoxFit fit = BoxFit.contain,
  }) {
    return SvgPicture.asset(
      name.toImgPath(format: format, directory: directory),
      width: width,
      height: height,
      colorFilter:
          color != null ? ColorFilter.mode(color, BlendMode.srcIn) : null,
      fit: BoxFit.fill,
    );
  }

  static Future<String> faultReportPath() async {
    var tempDir = await getTemporaryDirectory();
    Directory directory = Directory('${tempDir.path}/faultReport');
    if (!directory.existsSync()) {
      directory.createSync();
      if (kDebugMode) {
        print('文档初始化成功，文件保存路径为 ${directory.path}');
      }
    }
    return directory.path;
  }

  static bool isVideo(String filePath) {
    var ext = filePath.toLowerCase();
    return ext.endsWith(".mp4") ||
        ext.endsWith(".avi") ||
        ext.endsWith(".wmv") ||
        ext.endsWith(".rmvb") ||
        ext.endsWith(".mpg") ||
        ext.endsWith(".mpeg") ||
        ext.endsWith(".mov") ||
        ext.endsWith(".3gp");
  }

  static closeKeyboard({BuildContext? context}){
    FocusScope.of(context ?? Get.context!).requestFocus(FocusNode());
  }

  static limitText(TextEditingController controller,{int length = 200}){
    if(controller.text.length > length){
      var newStr = controller.text.substring(0,length);
      controller.text = newStr;
    }
  }

  static copyIn(BuildContext context,String? value){
    Clipboard.setData( ClipboardData(text: value ?? ""));
    SmartDialog.showToast("已复制到粘贴板");
    // ScaffoldMessenger.of(context).showSnackBar(
    //   const SnackBar(content: Text('已复制到粘贴板')),
    // );
  }
}

extension StringUtils on String {
  // String toMd5() {
  //   return md5.convert(utf8.encode(this)).toString();
  // }
  //
  // /*
  // * Base64加密
  // */
  // static String encodeBase64(String data) {
  //   var content = utf8.encode(data);
  //   var digest = base64Encode(content);
  //   return digest;
  // }
  //
  // /*
  // * Base64解密
  // */
  // static String decodeBase64(String data) {
  //   return String.fromCharCodes(base64Decode(data));
  // }
  //
  // static Map<String, dynamic> toMap(String data) {
  //   return convert.jsonDecode(data);
  // }
  //
  // static String toJsonStr(Map<String, dynamic> data) {
  //   return convert.jsonEncode(data);
  // }

  String toImgPath({String format = 'png', String? directory}) {
    if (contains(".")) {

      if (directory != null) {
        return 'assets/$directory/$this';
      }
      return 'assets/images/$this';
    }
    if (directory != null) {
      return 'assets/$directory/$this.$format';
    }
    return 'assets/images/$this.$format';
  }
  Color get toColor {
    return Color(int.parse(substring(1), radix: 16) | 0xFF000000);
  }
}

extension IntExt on int? {
  toDefault() {
    return this == null ? "--" : toString();
  }
}


extension PercentDoubleExt on double? {
  String toPercentStr() {
    return "${((this ?? 0) * 100.0).round()}%";
  }
}

extension PercentageNumExt on num? {
  String toPercentStr() {
    return "${((this ?? 0) * 100.0).round()}%";
  }
}

extension GlobalKeyExtension on GlobalKey {
  get getSize {
    var renderBox = currentContext?.findRenderObject() as RenderBox;
    return renderBox;
  }

  get getOffset {
    var renderBox = currentContext?.findRenderObject() as RenderBox;
    return renderBox.localToGlobal(Offset.zero);
  }

  get getMaxY {
    var renderBox = currentContext?.findRenderObject() as RenderBox;
    var offset = renderBox.localToGlobal(Offset.zero);
    return offset.dy + renderBox.size.height;
  }
}


class LabelValue {
  String label;
  dynamic value;
  bool checked;
  dynamic defaultValue;
  dynamic time;
  LabelValue({required this.label, required this.value, this.checked = false,this.defaultValue,this.time});
}

class ElevatedButtonWidget extends ElevatedButton {
   const ElevatedButtonWidget(
      {Key? key,
        required VoidCallback onPressed,
        required Widget child,
        VoidCallback? onLongPress,
        ButtonStyle? style,
        FocusNode? focusNode,
        bool autofocus = false,
        Clip clipBehavior = Clip.none,
        this.border,
        this.textColor,
        this.backgroundColor,
        this.elevation = 0,
        this.size,
        this.isEnable = true,
        this.alignment = Alignment.center,
        this.padding,
      })
      : super(
    key: key,
    onPressed: onPressed,
    onLongPress: onLongPress,
    style: style,
    focusNode: focusNode,
    autofocus: autofocus,
    clipBehavior: clipBehavior,
    child: child,
  );
  final OutlinedBorder? border;
  final Color? textColor;
  final Color? backgroundColor;
  final double? elevation;
  final Size? size;
  final bool isEnable;
  final AlignmentGeometry? alignment;
  final EdgeInsetsGeometry? padding;
  @override
  ButtonStyle? get style {
    if (border != null || size != null || backgroundColor != null) {
      ButtonStyle oneStyle = ButtonStyle(
        shape: MaterialStateProperty.all(border),
        // foregroundColor: backgroundColor != null?MaterialStateProperty.all(backgroundColor): super.style.backgroundColor,
        foregroundColor: MaterialStateProperty.all(textColor),
        backgroundColor: MaterialStateProperty.all(backgroundColor),
        elevation: MaterialStateProperty.all(elevation),
        minimumSize: size != null ? MaterialStateProperty.all(size) : null,
        overlayColor:  MaterialStateProperty.all(Colors.transparent),
        alignment: alignment,
        padding: MaterialStateProperty.all(padding ?? const EdgeInsets.symmetric(horizontal: 5))
      );
      return oneStyle;
    }
    return super.style;
  }

  @override
  VoidCallback? get onPressed => isEnable?super.onPressed : null;
}

